--[[ =========================================================================
   ROCKET CASINO -- Enseigne animee "Team Rocket" pour CC:Tweaked
   -------------------------------------------------------------------------
   * Palette 16 couleurs redefinie (rouge Rocket, or, neon rose)
   * Cadre marquee facon Vegas : ampoules qui defilent + neon qui pulse
   * Pokeball qui tourne reellement (bande orientee par un angle)
   * Grand R avec ombre portee et reflet metallique qui balaye la lettre
   * Titre en fonte 5x7 avec degrade or->rouge, balayage lumineux et
     micro-scintillement de neon fatigue
   * Bandeau defilant en bas + compteur de jackpot qui monte
   * Clic sur le moniteur = "JACKPOT !" : flash, confettis, sirene visuelle
   * Rendu par framebuffer : 1 seul blit par ligne => zero clignotement
   -------------------------------------------------------------------------
   Usage :  pastebin/copie dans rocket_casino.lua puis "rocket_casino"
   Sortie :  Ctrl+T
========================================================================= ]]

--------------------------------------------------------------------------
-- 1. CONFIGURATION
--------------------------------------------------------------------------
local CFG = {
  monitorName   = nil,      -- nil = detection auto du premier moniteur
  textScale     = 0.5,      -- 0.5 = pixels les plus fins
  fps           = 12,

  spinSpeed     = 0.45,     -- vitesse de rotation de la pokeball (rad/s)
  chaseSpeed    = 6,        -- vitesse des ampoules du cadre (cases/s)
  shimmerSpeed  = 26,       -- vitesse du reflet sur le R
  tickerSpeed   = 8,        -- vitesse du bandeau (cases/s)

  sparkles      = true,     -- petites etoiles dans le fond
  sparkleCount  = 42,
  neonFlicker   = true,     -- le titre "grille" de temps en temps

  jackpotStart  = 128450,
  jackpotRate   = 173,      -- pieces gagnees par seconde

  messages = {              -- bandeau du bas (majuscules, sans accents)
    "BIENVENUE AU ROCKET CASINO",
    "MACHINES A SOUS - BLACKJACK - ROULETTE - VOLTORBE FLIP",
    "PREPAREZ-VOUS AU COMBAT... ET MEME AU DOUBLE",
    "LA BANQUE GAGNE TOUJOURS. SAUF SI VOUS ETES PLUS RAPIDE",
    "TOUCHEZ L ECRAN POUR TENTER VOTRE CHANCE",
  },
}

--------------------------------------------------------------------------
-- 2. PALETTE (index hexa CC -> couleur RGB)
--------------------------------------------------------------------------
local PAL = {
  ["0"] = 0xffffff, -- blanc pur
  ["1"] = 0xff7a18, -- orange enseigne
  ["2"] = 0xff2f8f, -- magenta neon
  ["3"] = 0xc3c7d4, -- argent (bande de la pokeball)
  ["4"] = 0xffd23f, -- or
  ["5"] = 0x9dff5c, -- vert citron (confettis)
  ["6"] = 0xff5fb0, -- rose neon
  ["7"] = 0x14141c, -- gris tres sombre (panneau)
  ["8"] = 0x3a3a4c, -- charbon (calotte claire de la pokeball)
  ["9"] = 0x35e8ff, -- cyan (eclat)
  ["a"] = 0x4b1d6e, -- violet
  ["b"] = 0x1b3a8f, -- bleu profond
  ["c"] = 0x7a0f16, -- rouge sombre
  ["d"] = 0x2fbf5a, -- vert
  ["e"] = 0xd11f2a, -- ROUGE ROCKET
  ["f"] = 0x000000, -- noir
}

--------------------------------------------------------------------------
-- 3. FONTE 5x7 (extensible : ajoutez vos caracteres ici)
--------------------------------------------------------------------------
local FONT = {
  A="01110/10001/10001/11111/10001/10001/10001",
  B="11110/10001/10001/11110/10001/10001/11110",
  C="01110/10001/10000/10000/10000/10001/01110",
  D="11110/10001/10001/10001/10001/10001/11110",
  E="11111/10000/10000/11110/10000/10000/11111",
  F="11111/10000/10000/11110/10000/10000/10000",
  G="01110/10001/10000/10111/10001/10001/01111",
  H="10001/10001/10001/11111/10001/10001/10001",
  I="11111/00100/00100/00100/00100/00100/11111",
  J="00111/00010/00010/00010/00010/10010/01100",
  K="10001/10010/10100/11000/10100/10010/10001",
  L="10000/10000/10000/10000/10000/10000/11111",
  M="10001/11011/10101/10101/10001/10001/10001",
  N="10001/11001/10101/10011/10001/10001/10001",
  O="01110/10001/10001/10001/10001/10001/01110",
  P="11110/10001/10001/11110/10000/10000/10000",
  Q="01110/10001/10001/10001/10101/10010/01101",
  R="11110/10001/10001/11110/10100/10010/10001",
  S="01111/10000/10000/01110/00001/00001/11110",
  T="11111/00100/00100/00100/00100/00100/00100",
  U="10001/10001/10001/10001/10001/10001/01110",
  V="10001/10001/10001/10001/10001/01010/00100",
  W="10001/10001/10001/10101/10101/11011/10001",
  X="10001/10001/01010/00100/01010/10001/10001",
  Y="10001/10001/01010/00100/00100/00100/00100",
  Z="11111/00001/00010/00100/01000/10000/11111",
  ["0"]="01110/10011/10101/10101/11001/10001/01110",
  ["1"]="00100/01100/00100/00100/00100/00100/01110",
  ["2"]="01110/10001/00001/00110/01000/10000/11111",
  ["3"]="11111/00010/00100/00010/00001/10001/01110",
  ["4"]="00010/00110/01010/10010/11111/00010/00010",
  ["5"]="11111/10000/11110/00001/00001/10001/01110",
  ["6"]="00110/01000/10000/11110/10001/10001/01110",
  ["7"]="11111/00001/00010/00100/01000/01000/01000",
  ["8"]="01110/10001/10001/01110/10001/10001/01110",
  ["9"]="01110/10001/10001/01111/00001/00010/01100",
  [" "]="00000/00000/00000/00000/00000/00000/00000",
  ["!"]="00100/00100/00100/00100/00100/00000/00100",
  ["*"]="00000/10101/01110/11111/01110/10101/00000",
  ["$"]="00100/01111/10100/01110/00101/11110/00100",
  ["-"]="00000/00000/00000/11111/00000/00000/00000",
}

local GLYPH = {}
for ch, def in pairs(FONT) do
  local rows = {}
  for r in def:gmatch("[^/]+") do rows[#rows+1] = r end
  GLYPH[ch] = rows
end

--------------------------------------------------------------------------
-- 4. LE GRAND "R" (14 x 16)
--------------------------------------------------------------------------
local R_SPRITE = {
  "##########....",
  "############..",
  "###......####.",
  "###.......###.",
  "###.......###.",
  "###.......###.",
  "###......####.",
  "############..",
  "##########....",
  "###...###.....",
  "###....###....",
  "###.....###...",
  "###......###..",
  "###.......###.",
  "###.......###.",
  "###........###",
}

--------------------------------------------------------------------------
-- 5. MONITEUR + FRAMEBUFFER
--------------------------------------------------------------------------
local mon
if CFG.monitorName then mon = peripheral.wrap(CFG.monitorName)
else mon = peripheral.find("monitor") end
if not mon then error("Aucun moniteur trouve. Colle un moniteur au bloc ordinateur.", 0) end

mon.setTextScale(CFG.textScale)
for hex, rgb in pairs(PAL) do
  mon.setPaletteColour(2 ^ tonumber(hex, 16), rgb)
end

local W, H
local ct, cf, cb   -- char / foreground / background

local function fbInit()
  W, H = mon.getSize()
  ct, cf, cb = {}, {}, {}
  for y = 1, H do
    ct[y], cf[y], cb[y] = {}, {}, {}
    for x = 1, W do ct[y][x], cf[y][x], cb[y][x] = " ", "f", "f" end
  end
end

local function clear(bg)
  bg = bg or "f"
  for y = 1, H do
    local rt, rf, rb = ct[y], cf[y], cb[y]
    for x = 1, W do rt[x], rf[x], rb[x] = " ", "f", bg end
  end
end

-- pixel plein (on peint le fond de la case)
local function px(x, y, bg)
  bg = bg or "f"
  if x >= 1 and x <= W and y >= 1 and y <= H then
    local ix, iy = math.floor(x), math.floor(y)
    ct[iy][ix], cf[iy][ix], cb[iy][ix] = " ", "f", bg
  end
end

local function putc(x, y, ch, fg, bg)
  if x >= 1 and x <= W and y >= 1 and y <= H then
    ct[y][x] = ch
    cf[y][x] = fg
    if bg then cb[y][x] = bg end
  end
end

local function writeStr(x, y, s, fg, bg)
  for i = 1, #s do putc(x + i - 1, y, s:sub(i, i), fg, bg) end
end

local function push()
  for y = 1, H do
    mon.setCursorPos(1, y)
    mon.blit(table.concat(ct[y]), table.concat(cf[y]), table.concat(cb[y]))
  end
end

--------------------------------------------------------------------------
-- 6. OUTILS
--------------------------------------------------------------------------
local function now()
  if os.epoch then return os.epoch("utc") / 1000 end
  return os.clock()
end

local function fmtNum(n)
  local s = tostring(math.floor(n))
  local out = ""
  while #s > 3 do out = " " .. s:sub(-3) .. out; s = s:sub(1, -4) end
  return s .. out
end

-- dessine un sprite "##/.." avec facteur d'echelle et fonction de couleur
local function drawSprite(rows, x0, y0, sx, sy, colFn)
  for ry = 1, #rows do
    local row = rows[ry]
    for rx = 1, #row do
      if row:sub(rx, rx) ~= "." then
        local bx = x0 + (rx - 1) * sx
        local by = y0 + (ry - 1) * sy
        for iy = 0, sy - 1 do
          for ix = 0, sx - 1 do
            px(bx + ix, by + iy, colFn(bx + ix, by + iy, rx, ry))
          end
        end
      end
    end
  end
end

-- dessine du texte en fonte 5x7
local function drawBigText(x0, y0, text, sx, sy, colFn)
  local cx = x0
  for i = 1, #text do
    local g = GLYPH[text:sub(i, i)] or GLYPH[" "]
    for ry = 1, 7 do
      local row = g[ry]
      for rx = 1, 5 do
        if row:sub(rx, rx) == "1" then
          local bx = cx + (rx - 1) * sx
          local by = y0 + (ry - 1) * sy
          for iy = 0, sy - 1 do
            for ix = 0, sx - 1 do
              px(bx + ix, by + iy, colFn(bx + ix, by + iy, rx, ry, i))
            end
          end
        end
      end
    end
    cx = cx + 5 * sx + sx  -- espace inter-lettres proportionnel
  end
end

local function bigTextWidth(text, sx)
  return #text * (5 * sx + sx) - sx
end

--------------------------------------------------------------------------
-- 7. MISE EN PAGE (recalculee a chaque redimensionnement)
--------------------------------------------------------------------------
local L = {}
local stars = {}

local TITLE = "ROCKET CASINO"

local function layout()
  fbInit()

  L.border = (W >= 46 and H >= 24) and 3 or 2
  L.x1, L.y1 = L.border + 1, L.border + 1
  L.x2, L.y2 = W - L.border, H - L.border
  local availW = L.x2 - L.x1 + 1
  local availH = L.y2 - L.y1 + 1

  -- Titre : plus grosse echelle qui tient sur une ligne, sinon sur deux
  -- (ratio 3:2 pour compenser les cases plus hautes que larges)
  local candidates = { {5,3}, {3,2}, {2,1}, {1,1} }
  L.lines = { TITLE }
  L.tsx, L.tsy = 1, 1
  L.bigTitle = false
  for _, set in ipairs({ { TITLE }, { "ROCKET", "CASINO" } }) do
    for _, c in ipairs(candidates) do
      local w = 0
      for _, ln in ipairs(set) do w = math.max(w, bigTextWidth(ln, c[1])) end
      local h = #set * 7 * c[2] + (#set - 1) * c[2]
      if w <= availW and h + 12 <= availH then
        L.lines, L.tsx, L.tsy, L.bigTitle = set, c[1], c[2], true
        break
      end
    end
    if L.bigTitle then break end
  end

  L.titleW = 0
  for _, ln in ipairs(L.lines) do
    L.titleW = math.max(L.titleW, bigTextWidth(ln, L.tsx))
  end
  L.titleX = L.x1 + math.floor((availW - L.titleW) / 2)
  L.titleY = L.y1 + 1
  L.titleH = L.bigTitle and (#L.lines * 7 * L.tsy + (#L.lines - 1) * L.tsy) or 1

  -- Bandeau du bas
  L.tickerY = L.y2
  L.tickerX = L.x1 + 1
  L.tickerW = availW - 2

  -- Zone logo
  local logoTop = L.titleY + L.titleH + 1
  local logoBot = L.tickerY - 2
  L.cy = (logoTop + logoBot) / 2
  L.cx = (L.x1 + L.x2) / 2
  local ry = math.floor((logoBot - logoTop) / 2)
  local rx = math.floor(ry * 1.6)
  if rx > (availW - 4) / 2 then
    rx = math.floor((availW - 4) / 2)
    ry = math.floor(rx / 1.6)
  end
  L.rx, L.ry = math.max(4, rx), math.max(3, ry)

  -- Taille du R : ~72% de la hauteur de la ball
  L.rsy = math.max(1, math.floor((L.ry * 2 * 0.62) / 16))
  L.rsx = math.max(1, math.floor(L.rsy * 1.5 + 0.5))
  while 14 * L.rsx > L.rx * 1.25 and L.rsx > 1 do L.rsx = L.rsx - 1 end
  L.shadow = (L.rsx >= 3) and 2 or 1
  L.rw, L.rh = 14 * L.rsx, 16 * L.rsy
  L.rX = math.floor(L.cx - L.rw / 2)
  L.rY = math.floor(L.cy - L.rh / 2)

  -- Anneaux du cadre
  L.rings = {}
  for i = 0, L.border - 1 do
    local cells = {}
    local x1, y1, x2, y2 = 1 + i, 1 + i, W - i, H - i
    for x = x1, x2 do cells[#cells+1] = {x, y1} end
    for y = y1 + 1, y2 do cells[#cells+1] = {x2, y} end
    for x = x2 - 1, x1, -1 do cells[#cells+1] = {x, y2} end
    for y = y2 - 1, y1 + 1, -1 do cells[#cells+1] = {x1, y} end
    L.rings[i + 1] = cells
  end

  -- Etoiles de fond
  stars = {}
  if CFG.sparkles then
    for i = 1, CFG.sparkleCount do
      stars[i] = {
        x = math.random(L.x1, L.x2),
        y = math.random(L.y1, L.y2),
        p = math.random() * 6.283,
        s = 0.6 + math.random() * 1.8,
      }
    end
  end
end

--------------------------------------------------------------------------
-- 8. ETAT
--------------------------------------------------------------------------
local t0        = now()
local jackpot   = CFG.jackpotStart
local flash     = 0        -- secondes restantes de mode JACKPOT
local confetti  = {}
local flickerTo = 0        -- fin du micro-coupure neon
local flickerNx = 3

local function burst(bx, by)
  flash = 2.4
  confetti = {}
  local cols = { "4", "1", "e", "0", "6", "5", "9" }
  for i = 1, 90 do
    local a = math.random() * 6.283
    local sp = 6 + math.random() * 26
    confetti[i] = {
      x = bx, y = by,
      vx = math.cos(a) * sp,
      vy = math.sin(a) * sp * 0.55 - 6,
      c = cols[math.random(#cols)],
      life = 1.2 + math.random() * 1.2,
    }
  end
end

--------------------------------------------------------------------------
-- 9. COUCHES DE RENDU
--------------------------------------------------------------------------
local function drawBackground(t)
  clear("f")
  -- leger halo violet derriere le logo
  for y = L.y1, L.y2 do
    for x = L.x1, L.x2 do
      local dx, dy = (x - L.cx) / (L.rx * 1.22), (y - L.cy) / (L.ry * 1.22)
      if dx * dx + dy * dy < 1 then px(x, y, "7") end
    end
  end
  for _, s in ipairs(stars) do
    local b = math.sin(t * s.s + s.p)
    if b > 0.86 then px(s.x, s.y, "0")
    elseif b > 0.6 then px(s.x, s.y, "8") end
  end
end

local function drawFrame(t)
  local chase = { "4", "1", "e", "1" }
  local step = math.floor(t * CFG.chaseSpeed)
  for ri, cells in ipairs(L.rings) do
    if ri == 1 then
      -- ampoules qui defilent
      for i, c in ipairs(cells) do
        local k = (i + step * (ri % 2 == 1 and 1 or -1)) % 8
        local col
        if flash > 0 then
          col = ((i + step * 2) % 4 < 2) and "0" or "4"
        elseif k < 2 then col = "0"
        elseif k < 4 then col = chase[1]
        elseif k < 6 then col = chase[3]
        else col = "c" end
        px(c[1], c[2], col)
      end
    elseif ri == 2 then
      for _, c in ipairs(cells) do px(c[1], c[2], "f") end
    else
      -- liseret neon qui respire
      local pulse = (math.sin(t * 2.2) + 1) / 2
      local col = pulse > 0.66 and "6" or (pulse > 0.33 and "2" or "a")
      if flash > 0 then col = "0" end
      for _, c in ipairs(cells) do px(c[1], c[2], col) end
    end
  end
end

local BRIGHTER = { f = "7", ["7"] = "8" }

local function drawPokeball(t)
  local th = t * CFG.spinSpeed
  local st, ctv = math.sin(th), math.cos(th)
  local rimPulse = (math.sin(t * 3) + 1) / 2
  local rim = flash > 0 and "0" or (rimPulse > 0.5 and "6" or "2")

  for y = math.floor(L.cy - L.ry) - 1, math.ceil(L.cy + L.ry) + 1 do
    for x = math.floor(L.cx - L.rx) - 1, math.ceil(L.cx + L.rx) + 1 do
      local dx = (x - L.cx) / L.rx
      local dy = (y - L.cy) / L.ry
      local d = math.sqrt(dx * dx + dy * dy)
      if d <= 1.02 then
        local col
        local n = dx * (-st) + dy * ctv   -- distance signee a la bande
        if d > 0.955 then
          col = rim                        -- anneau neon
        elseif d > 0.90 then
          col = "c"                        -- halo rouge sombre interieur
        elseif math.abs(n) < 0.085 then
          col = "3"                        -- bande argent
        elseif math.abs(n) < 0.15 then
          col = "f"                        -- lisere noir de la bande
        elseif n < 0 then
          col = (d < 0.72) and "8" or "7"  -- calotte claire
        else
          col = (d < 0.72) and "7" or "f"  -- calotte sombre
        end
        -- bouton central
        local bd = math.sqrt(dx * dx + dy * dy)
        if bd < 0.13 then col = "f" end
        if bd < 0.10 then col = "3" end
        if bd < 0.05 then col = flash > 0 and "0" or "e" end
        -- gloss : source lumineuse fixe en haut a gauche
        local hd = math.sqrt((dx + 0.42) ^ 2 + (dy + 0.42) ^ 2)
        if hd < 0.34 and d < 0.9 and (col == "f" or col == "7") then
          col = BRIGHTER[col] or col
          if hd < 0.16 then col = BRIGHTER[col] or col end
        end
        px(x, y, col)
      end
    end
  end
end

local function drawR(t)
  local sweep = (t * CFG.shimmerSpeed) % (L.rw + L.rh + 60) - 30
  local function colR(x, y)
    if flash > 0 then
      return ((x + y + math.floor(t * 30)) % 6 < 3) and "4" or "0"
    end
    local s = (x - L.rX) + (y - L.rY) * 1.4 - sweep
    if s > -1.2 and s < 1.2 then return "0" end
    if s > -3.5 and s < 3.5 then return "1" end
    if (y - L.rY) < L.rh * 0.18 then return "e" end
    return "e"
  end
  -- ombre portee
  drawSprite(R_SPRITE, L.rX + L.shadow, L.rY + L.shadow, L.rsx, L.rsy, function() return "f" end)
  drawSprite(R_SPRITE, L.rX, L.rY, L.rsx, L.rsy, colR)
end

local function drawTitle(t)
  local dim = false
  if CFG.neonFlicker then
    if t > flickerNx then
      flickerTo = t + 0.06 + math.random() * 0.12
      flickerNx = t + 4 + math.random() * 7
    end
    dim = t < flickerTo
  end

  if not L.bigTitle then
    local s = TITLE
    writeStr(math.floor((W - #s) / 2) + 1, L.titleY, s, dim and "c" or "4", "f")
    return
  end


  local sweep = (t * 22) % (L.titleW + 90) - 45
  local function colT(x, y, gx, gy, idx)
    if flash > 0 then
      return ((idx + math.floor(t * 12)) % 3 == 0) and "0" or "4"
    end
    if dim then return "c" end
    local s = (x - L.titleX) - sweep
    if s > -1.5 and s < 1.5 then return "0" end
    if s > -4 and s < 4 then return "4" end
    -- degrade vertical or -> rouge (metal chaud)
    if gy <= 2 then return "4"
    elseif gy <= 4 then return "1"
    else return "e" end
  end
  local sh = (L.tsx >= 3) and 2 or 1
  for i, ln in ipairs(L.lines) do
    local w = bigTextWidth(ln, L.tsx)
    local x = L.titleX + math.floor((L.titleW - w) / 2)
    local y = L.titleY + (i - 1) * (7 * L.tsy + L.tsy)
    drawBigText(x + sh, y + sh, ln, L.tsx, L.tsy, function() return "f" end)
    drawBigText(x, y, ln, L.tsx, L.tsy, colT)
  end
end

-- bandeau defilant --------------------------------------------------------
local tickTxt, tickCol = "", ""
local tickBuilt = -1

local function buildTicker(t)
  if t - tickBuilt < 1 then return end
  tickBuilt = t
  local parts = {}
  local cols  = {}
  local pal   = { "4", "0", "6", "1" }
  for i, m in ipairs(CFG.messages) do
    parts[#parts+1] = m
    cols[#cols+1]   = pal[((i - 1) % #pal) + 1]
    parts[#parts+1] = "   * * *   "
    cols[#cols+1]   = "e"
    if i == 1 then
      parts[#parts+1] = "JACKPOT " .. fmtNum(jackpot) .. " P$"
      cols[#cols+1]   = "5"
      parts[#parts+1] = "   * * *   "
      cols[#cols+1]   = "e"
    end
  end
  tickTxt, tickCol = "", ""
  for i, p in ipairs(parts) do
    tickTxt = tickTxt .. p
    tickCol = tickCol .. string.rep(cols[i], #p)
  end
end

local function drawTicker(t)
  buildTicker(t)
  local n = #tickTxt
  if n == 0 then return end
  local off = math.floor(t * CFG.tickerSpeed) % n
  for i = 0, L.tickerW - 1 do
    local idx = ((off + i) % n) + 1
    putc(L.tickerX + i, L.tickerY, tickTxt:sub(idx, idx), tickCol:sub(idx, idx), "f")
  end
  -- separateur discret au-dessus
  for x = L.x1, L.x2 do px(x, L.tickerY - 1, "7") end
end

local function drawConfetti(dt)
  for i = #confetti, 1, -1 do
    local c = confetti[i]
    c.life = c.life - dt
    if c.life <= 0 then
      table.remove(confetti, i)
    else
      c.x = c.x + c.vx * dt
      c.y = c.y + c.vy * dt
      c.vy = c.vy + 34 * dt
      px(c.x, c.y, c.life < 0.35 and "c" or c.c)
    end
  end
end

local function drawJackpotBanner(t)
  if flash <= 0 then return end
  local msg = "JACKPOT !"
  local blink = math.floor(t * 8) % 2 == 0
  -- on prend la plus grosse echelle qui rentre dans la largeur utile
  local avail = L.x2 - L.x1 + 1
  local sx, sy = nil, nil
  for _, c in ipairs({ {4,3}, {3,2}, {2,1}, {1,1} }) do
    if bigTextWidth(msg, c[1]) <= avail then sx, sy = c[1], c[2]; break end
  end
  if not sx then   -- ecran trop etroit : version texte simple
    local y = math.floor(L.cy)
    local x = math.floor((W - #msg) / 2) + 1
    for i = -1, #msg do px(x + i, y, "f") end
    writeStr(x, y, msg, blink and "0" or "4", "f")
    return
  end
  local w, h = bigTextWidth(msg, sx), 7 * sy
  local x = math.floor((W - w) / 2) + 1
  local y = math.floor(L.cy - h / 2)
  for yy = y - sy, y + h + sy - 1 do
    for xx = x - 2 * sx, x + w + 2 * sx - 1 do px(xx, yy, "f") end
  end
  drawBigText(x, y, msg, sx, sy, function(_, _, _, gy)
    if blink then return gy <= 3 and "0" or "4" end
    return gy <= 3 and "4" or "1"
  end)
end

--------------------------------------------------------------------------
-- 10. BOUCLE PRINCIPALE
--------------------------------------------------------------------------
local function draw(dt)
  local t = now() - t0
  jackpot = jackpot + CFG.jackpotRate * dt
  if flash > 0 then flash = flash - dt end

  drawBackground(t)
  drawPokeball(t)
  drawR(t)
  drawTitle(t)
  drawTicker(t)
  drawConfetti(dt)
  drawJackpotBanner(t)
  drawFrame(t)
  push()
end

local function main()
  layout()
  mon.setBackgroundColour(colours.black)
  mon.clear()
  local last = now()
  local timer = os.startTimer(1 / CFG.fps)
  while true do
    local ev, p1, p2, p3 = os.pullEvent()
    if ev == "timer" and p1 == timer then
      local t = now()
      local dt = math.min(t - last, 0.25)
      last = t
      draw(dt)
      timer = os.startTimer(1 / CFG.fps)
    elseif ev == "monitor_resize" then
      layout()
      mon.clear()
    elseif ev == "monitor_touch" then
      burst(p2, p3)
      jackpot = CFG.jackpotStart + math.random(0, 9999)
      tickBuilt = -1
    end
  end
end

local ok, err = pcall(main)
mon.setBackgroundColour(colours.black)
mon.setTextColour(colours.white)
mon.clear()
mon.setCursorPos(1, 1)
for hex in pairs(PAL) do
  local c = 2 ^ tonumber(hex, 16)
  mon.setPaletteColour(c, term.nativePaletteColour and term.nativePaletteColour(c) or PAL[hex])
end
if not ok and err ~= "Terminated" then error(err, 0) end
print("Rocket Casino : enseigne arretee.")